package com.wao.base.security.tenant;

import com.wao.base.config.Constants;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;

/**
 * Created by Arthur on 2017/4/10.
 * 多租户数据库标识符提供器默认实现
 */
public class TenantIdentifierResolver implements CurrentTenantIdentifierResolver {

    private static final ThreadLocal<String> threadTenantIdentifier = new ThreadLocal<String>();

    /**
     * 获取当前租户标识符
     *
     * @return
     */
    public static String getCurrentTenantIdentifier() {
        String currentTenantIdentifier = threadTenantIdentifier.get();
        if (currentTenantIdentifier != null)
            return getCurrentTenantIdentifier();
        return Constants.DEFAULT_TENANT_ID;
    }

    /**
     * 设置当前租户标识符
     *
     * @param tenantIdentifier
     */
    public static void setCurrentTenantIdentifier(String tenantIdentifier) {
        threadTenantIdentifier.set(tenantIdentifier);
    }

    @Override
    public String resolveCurrentTenantIdentifier() {
        return getCurrentTenantIdentifier();
    }

    @Override
    public boolean validateExistingCurrentSessions() {
        return true;
    }
}
